/**
 * @author: zhazhjie
 * @email: zhazhjie@vip.qq.com
 * @date: 2018-11-05 10:31:38
 * @version: 1.0
 */

import axios from 'axios'
import store from '../store'
import errorCode from './errorCode'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import {Message} from 'element-ui'
import {getToken} from "../utils/util";

const API_ROOT = process.env.VUE_APP_API_ROOT;

axios.defaults.timeout = 30000;
axios.defaults.baseURL = API_ROOT;
// 跨域请求，允许保存cookie
axios.defaults.withCredentials = true;
// request拦截
axios.interceptors.request.use(config => {
  NProgress.start();
  config.headers['token'] = getToken();
  return config;
}, error => {
  return Promise.reject(error);
});
// response拦截
axios.interceptors.response.use(res => {
  NProgress.done();
  return res.data;
}, error => {
  NProgress.done();
  let {response = {}} = error;
  let {status, data = {}, code} = response;
  switch (status) {
    case 400:
      Message({
        message: data.msg,
        type: 'warning'
      });
      return Promise.reject(data);
    case 401:
      store.commit("logout");
      return Promise.reject(error);
    default:
      Message({
        message: data.msg || errorCode[status] || errorCode['default'],
        type: 'error'
      });
      return Promise.reject(error);
  }
});

export default axios
